const router = require('koa-router')()
const { SuccessModel, FailModel } = require('../resModel/index')
const jwt = require('jsonwebtoken');
const { exec } = require('../db')
const { getPassword } = require('../extends/crypto')

const secret_key = '1808A_Students.fw'

// 路由前缀添加抽离
// router.prefix('/api')
/**
 * * 1. 登陆  /api/login
      2. 注册 /api/register
      3. 作者添加接口： post   /api/user
      4. 作者删除接口： delete /api/user/:id
      5. 作者修改接口： put    /api/user/:id
      6. 作者查看接口： get    /api/user

   async await 将异步代码书写为同步行为：（书写的就是同步代码）

   this.a().then(res=> {}).catch(e => {} )
   try {} catch(e) {} : 捕捉同步错误

 */

const auth = async (ctx, next) => {
  const { authorization } = ctx.request.headers;
  try {
    // 如果这个数据能校验处理，就说明当前的用户就是我的那个用户；
    const jwtData = jwt.verify(authorization, secret_key);
    // console.log('jwtData....:', jwtData)
    await next()
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: 'token校验失败',
      err
    }
  }
}

// 登陆
router.post('/api/login', async (ctx, next) => {
  const { username, password } = ctx.request.body;
  const data = await exec(`select * from users where username=? and password=?`,
  [username, getPassword(password)])
  // 生成token
  const token = jwt.sign({ ...data }, secret_key, { expiresIn: '1h' })
  if (data.length) {
    ctx.body = new SuccessModel({
      token
    }, '登陆成功')
  } else {
    ctx.body = new FailModel(data, '登陆失败')
  }
})

// 注册
router.post('/api/register', async (ctx, next) => {
  const { username, password, nickname, avatar } = ctx.request.body;
  // 1. 先查询数据库是否存在
  const queryData = await exec(`select * from users where username=?`,
  [username])
  if (queryData.length) {
    ctx.body = new FailModel('数据已经注册,请换一个名字再来')
  } else {
    const insertData = await exec(`
    insert into users (username, password, nickname, avatar) values (?, ?, ?, ?)`,
    [username, getPassword(password), nickname, avatar]);
    if (insertData.affectedRows) {
      ctx.body = new SuccessModel({id: insertData.insertId}, '数据添加成功')
    } else {
      ctx.body = new FailModel(data, '数据添加失败,请重试')
    }
  }
})

// 查看用户接口 分页功能 如果不传参数，展示默认前10条所有数据
router.get('/api/user',  async (ctx, next) => { // 中间件
  // console.log('headers....:', ctx.request.headers)
  const { page, size } = ctx.query;
  // 后台 验证
  const total = await exec(`select count(id) as total from users`)
  console.log('total.,...:', total)

  if (page && size) {
    const data = await exec(`select * from users order by id asc limit ? offset ?`,
    [Number(size), page * size]);
    // 查询当前表的总条数
    if (data.length) {
      ctx.body = new SuccessModel({data, total: total[0].total}, 'success')
    } else {
      ctx.body = new FailModel(data, 'success')
    }
  } else {
    const data = await exec(`select * from users order by id asc limit 10 offset 0`);
    ctx.body = new SuccessModel({data, total: total[0].total}, 'success')
  }
})

// 修改接口 params:id
router.put('/api/updateUser/:id', auth, async (ctx, next) => {
  const { password, nickname, avatar } = ctx.request.body;
  const { id } = ctx.params;
  const updateData = await exec(
    `update users set password=?, nickname=?, avatar=? where id=?`,
    [password, nickname, avatar, id]
  )
  if (updateData.affectedRows) {
    ctx.body = new SuccessModel('数据修改成功')
  } else {
    ctx.body = new FailModel('数据修改失败, 请重试')
  }
})

// 用户删除有什么问题？ 多表联系的删除；
// 1. 查询到 当前这个人有什么文章，
// 先删除用户； delete from  users
// 再删除文章； delete from blogs where author=1
// 删除用户接口 params:id
router.delete('/api/user/:id', auth, async () => {
  const { id } = ctx.params;
  // 1. 删除当前用户
  const deleteUsersData = await exec(`delete from users where id=?`, [id])
  if (deleteUsersData.affectedRows) {
    // 2. 删除当前用户文章
    const deleteBlogsData = await exec(`delete from blogs where author=?`, [id])
    if (deleteBlogsData.affectedRows) {
      ctx.body = new SuccessModel('数据删除成功')
    } else {
      ctx.body = new FailModel('数据删除失败')
    }
  } else {
    ctx.body = new FailModel('删除用户失败')
  }
})


module.exports = router